package org.HisCanvas.ChrisRiffle.JFlightLog.persist;

import java.util.Iterator;
import java.util.List;

import org.HisCanvas.ChrisRiffle.JFlightLog.dataModel.LogBook;
import org.HisCanvas.ChrisRiffle.JFlightLog.dataModel.LogBookRec;
import org.HisCanvas.ChrisRiffle.JFlightLog.logging.LogController;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


/**
 * HibernateController
 * 
 * @author RIF
 * 
 */
public class LogBookDAOHIbernate implements LogBookDAO, LogBookDbConstants
{

	
	private Session hibernateSession;
	
		
	/**
	 * init
	 */
	public void init() throws Exception{

		
		LogController.info("Getting Hibernate configuration files and building the Session Factory");
		
				
		SessionFactory sessionFactory = new Configuration().configure()
				.buildSessionFactory();

		
		LogController.info("Opening Hibernate Session");
		
		hibernateSession = sessionFactory.openSession();
		
	}
	
	
	/**
	 * closeSession
	 */
	public void close() throws Exception{
		
		try{
			hibernateSession.connection().createStatement().execute("SHUTDOWN");
			
		}catch (Exception e) {
			
			e.printStackTrace();
			
		}
		
		hibernateSession.close();		
	}
	
	
	
	/**
	 * Gets the etire logbook
	 * 
	 * @return
	 */
	public LogBook getLogBook() throws Exception {

		LogBook rLogBook = new LogBook();

		// Using from Clause
		String sqlQuery = "FROM LogBookRec " + LOGBOOK_TABLE;

		Query query = hibernateSession.createQuery(sqlQuery);

		List<LogBookRec> resultList = query.list();

		for (LogBookRec iRec : resultList) {

			rLogBook.getLogBookRecList().add(iRec);
		}

		return rLogBook;
	}


	/**
	 * Gets 
	 * 
	 * @return
	 */
	public LogBookRec getLogBookRec(int pPkId) throws Exception{
						
		LogBookRec rLogBookRec = null;
		
		 //Using from Clause
		  String sqlQuery ="FROM LogBookRec " + LOGBOOK_TABLE + " WHERE " 
			  + PK_ID + " = "  + pPkId;
		  
		  Query query = hibernateSession.createQuery(sqlQuery);
		  		  		  
		  for(Iterator it = query.iterate();it.hasNext();){
			  			
			  if(rLogBookRec != null){
				  
				  String errMsg = "pkId: " + pPkId + "not unique";
				  LogController.severe(errMsg);
				  throw new Exception(errMsg);
			  }
			  
			  rLogBookRec = (LogBookRec)it.next();			  						  			  
		   }	
		  
		  return rLogBookRec;
	}


	/**
	 * addLogBookRec
	 * 
	 * @param pLogBookRec
	 */
	public void addLogBookRec(LogBookRec pLogBookRec) throws Exception{
		
		Transaction hibernateTx = hibernateSession.beginTransaction();
								
		hibernateSession.save(pLogBookRec);
		
		hibernateTx.commit();
		hibernateSession.flush();
	}
	
	
	/**
	 * NOte the rec must have a primary key
	 * 
	 * 
	 */
	public void modifyLogBookRec(LogBookRec pLogBookRec) throws Exception{
		
		if(pLogBookRec == null){		
			
			String errMsg = "updateLogBookRec() was passed a null rec, Returning";
			LogController.severe(errMsg);
			return;
		}
		
		LogController.info("Updating logbookrec: " + pLogBookRec.getPrimaryKey());
		
		Transaction hibernateTx = hibernateSession.beginTransaction();
				
		hibernateSession.update(pLogBookRec);
		
		hibernateTx.commit();
		hibernateSession.flush();
	}
	
	
	/**
	 * deleteLogBookRec
	 * 
	 * @param pLogBookRec
	 */
	public void removeLogBookRec(LogBookRec pLogBookRec) throws Exception{

		String hql = "DELETE FROM " + LOGBOOK_TABLE 
			+ " WHERE " + PK_ID + " = " + pLogBookRec.getPrimaryKey();
		
		Query query = hibernateSession.createQuery(hql);

		int deletedRowCount = query.executeUpdate();

		if (deletedRowCount == 0) {
			
			String errMsg = "Failed Deleting pkId: " + pLogBookRec.getPrimaryKey();
			
			LogController.warning(errMsg);
			
			throw new Exception(errMsg);
			
		} else {
			
			LogController.info("Deleted row with pk_id: " + pLogBookRec.getPrimaryKey());
		}
	}
	

	
	/**
	 * testAddLogBookRec
	 */
	private void testAddLogBookRec() throws Exception{
	
		LogController.info("testAddLogBookRec()");
		
		LogBookRec myRec = new LogBookRec();
		
		myRec.setSafetyPilotName("HiBbYHiBbYHiBbYHiBbY");
		myRec.setAircraftType("HiBbY");
		
		addLogBookRec(myRec);
		
	}
	
	
	/**
	 * main
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
				
		LogController.info("HibernateController.main() starting up...");
		
//		testAddLogBookRec();
//		
//		closeSession();		
	}


	
	
}


